<template>
  <div class="db-management">
    <el-card>
      <div slot="header" class="card-header">
        <span>数据库管理</span>
        <div class="header-actions">
          <el-button type="primary" @click="handleSyncDatabases" :loading="syncing">
            <i class="el-icon-sync"></i> 同步数据库信息
          </el-button>
          <el-button @click="handleRefresh">
            <i class="el-icon-refresh"></i> 刷新
          </el-button>
        </div>
      </div>
      
      <div class="form-container">
        <el-form :inline="true" :model="searchForm" class="search-form">
          <el-form-item label="数据库配置：">
            <el-select v-model="searchForm.dbConfigId" placeholder="请选择数据库配置" style="width: 200px" @change="onDbConfigChange">
              <el-option v-for="config in dbConfigList" :key="config.id" :label="config.configName" :value="config.id"></el-option>
            </el-select>
          </el-form-item>
          
          <el-form-item label="数据库名称：">
            <el-input v-model="searchForm.dbName" placeholder="请输入数据库名称关键词" style="width: 200px" clearable></el-input>
          </el-form-item>
          
          <el-form-item>
            <el-button type="primary" @click="handleSearch">
              <i class="el-icon-search"></i> 搜索
            </el-button>
          </el-form-item>
        </el-form>
      </div>
      
      <div class="table-container">
        <el-table v-loading="loading" :data="databaseList" stripe style="width: 100%">
          <el-table-column type="index" width="50" label="序号"></el-table-column>
          <el-table-column prop="dbName" label="数据库名称" width="200"></el-table-column>
          <el-table-column prop="dbType" label="数据库类型" width="120"></el-table-column>
          <el-table-column prop="tablesCount" label="表数量" width="100"></el-table-column>
          <el-table-column prop="createTime" label="创建时间" width="180" :formatter="dateFormat"></el-table-column>
          <el-table-column label="操作" width="80" fixed="right">
            <template slot-scope="scope">
              <el-dropdown size="small">
                <el-button size="small" type="text">
                  <i class="el-icon-setting"></i> 操作<i class="el-icon-arrow-down el-icon--right"></i>
                </el-button>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item @click.native="handleEdit">
                    <i class="el-icon-edit"></i> 编辑配置
                  </el-dropdown-item>
                  <el-dropdown-item @click.native="handleViewTables(scope.row)">
                    <i class="el-icon-document"></i> 查看表
                  </el-dropdown-item>
                  <el-dropdown-item @click.native="handleSyncSchema(scope.row)">
                    <i class="el-icon-sync"></i> 同步表结构
                  </el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>
      </div>
      
      <div class="pagination" v-if="total > 0">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'DatabaseManagementList',
  data() {
    return {
      searchForm: {
        dbConfigId: '',
        dbName: ''
      },
      dbConfigList: [],
      databaseList: [],
      loading: false,
      syncing: false,
      total: 0,
      currentPage: 1,
      pageSize: 10
    };
  },
  methods: {
    // 获取数据库配置列表
    getDbConfigList() {
      this.$api.databaseConfigApi.getAll().then(data => {
        // http.js已经处理了响应格式，这里直接获取数据
        this.dbConfigList = data && data.data || [];
      }).catch(err => {
        console.error('获取数据库配置列表失败:', err);
        this.$message.error('获取数据库配置列表失败');
      });
    },
    
    // 数据库配置变更时获取数据库列表
    onDbConfigChange() {
      if (this.searchForm.dbConfigId) {
        this.getDatabaseList();
      } else {
        this.databaseList = [];
        this.total = 0;
      }
    },
    
    // 获取数据库列表
    getDatabaseList() {
      if (!this.searchForm.dbConfigId) {
        this.$message.warning('请先选择数据库配置');
        return;
      }
      
      this.loading = true;
      
      // 构建查询参数
      const params = {
        page: this.currentPage,
        pageSize: this.pageSize
      };
      
      if (this.searchForm.dbName.trim()) {
        params.dbName = this.searchForm.dbName;
      }
      
      this.$api.dbManagementApi.getDatabases(this.searchForm.dbConfigId, params).then(data => {
        // http.js已经处理了响应格式，这里直接获取数据
        console.log('获取数据库列表响应:', data);
        this.databaseList = data && data.data || [];
        this.total = this.databaseList.length;
        console.log('数据库列表数据:', this.databaseList);
      }).catch(err => {
        console.error('获取数据库列表失败:', err);
        this.$message.error('获取数据库列表失败');
        this.databaseList = [];
        this.total = 0;
      }).finally(() => {
        this.loading = false;
      });
    },
    
    // 搜索数据库
    handleSearch() {
      this.currentPage = 1;
      this.getDatabaseList();
    },
    
    // 查看数据库中的表
    handleViewTables(row) {
      // 跳转到表结构管理页面，并传入数据库配置ID和数据库名称
      this.$router.push({
        path: '/schema',
        query: {
          dbConfigId: this.searchForm.dbConfigId,
          databaseName: row.dbName
        }
      });
    },
    
    // 编辑数据库配置
    handleEdit() {
      if (this.searchForm.dbConfigId) {
        this.$router.push(`/db-management/edit/${this.searchForm.dbConfigId}`);
      } else {
        this.$message.warning('请先选择数据库配置');
      }
    },
    
    // 同步数据库表结构
    handleSyncSchema(row) {
      this.$confirm(`确定要同步"${row.dbName}"的表结构吗？`, '确认同步', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$api.dbManagementApi.syncSchema({
          dbConfigId: this.searchForm.dbConfigId,
          databaseName: row.dbName
        }).then(() => {
          this.$message.success('表结构同步成功');
        }).catch(err => {
          console.error('同步表结构失败:', err);
          this.$message.error('表结构同步失败');
        });
      }).catch(() => {
        this.$message.info('已取消同步');
      });
    },
    
    // 同步数据库信息
    handleSyncDatabases() {
      if (!this.searchForm.dbConfigId) {
        this.$message.warning('请先选择数据库配置');
        return;
      }
      
      this.$confirm('确定要从数据库配置同步数据库信息吗？这将会更新或添加数据库信息到系统中。', '确认同步', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.syncing = true;
        
        // 在api.js中，syncDatabases方法需要dbConfigId作为参数
        this.$api.dbManagementApi.syncDatabases(this.searchForm.dbConfigId).then(data => {
          // http.js已经处理了响应格式，不需要额外判断
          this.$message.success('数据库信息同步成功');
          // 同步成功后刷新列表
        console.log('同步数据库成功，准备刷新列表');
        this.getDatabaseList();
        }).catch(err => {
          console.error('同步数据库信息失败:', err);
          this.$message.error('同步数据库信息失败');
        }).finally(() => {
          this.syncing = false;
        });
      }).catch(() => {
        this.$message.info('已取消同步');
      });
    },
    
    // 刷新列表
    handleRefresh() {
      this.getDbConfigList();
      if (this.searchForm.dbConfigId) {
        this.getDatabaseList();
      }
    },
    
    // 分页大小变化
    handleSizeChange(size) {
      this.pageSize = size;
      this.getDatabaseList();
    },
    
    // 当前页码变化
    handleCurrentChange(current) {
      this.currentPage = current;
      this.getDatabaseList();
    },
    
    // 日期格式化
    dateFormat(row, column, cellValue) {
      if (cellValue) {
        const date = new Date(cellValue);
        return date.toLocaleString('zh-CN');
      }
      return '';
    }
  },
  mounted() {
    // 页面加载时获取数据库配置列表
    this.getDbConfigList();
    
    // 检查URL参数中的dbConfigId
    const dbConfigId = this.$route.query.dbConfigId;
    if (dbConfigId) {
      this.searchForm.dbConfigId = dbConfigId;
      // 延迟执行，确保dbConfigList已经加载完成
      setTimeout(() => {
        this.getDatabaseList();
      }, 500);
    }
  }
};
</script>

<style scoped>
.db-management {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.form-container {
  margin-top: 10px;
}

.search-form {
  padding: 10px 0;
}

.table-container {
  margin-top: 10px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>